package fr.utbm.gi.vi51.project.behavior.steering;

import java.util.List;
import java.util.Random;

import javax.vecmath.Point2d;
import javax.vecmath.Vector2d;

import fr.utbm.gi.vi51.project.behavior.EscapeBehaviour;

public class SteeringEscapeBehaviour implements EscapeBehaviour<SteeringBehaviourOutput> {

	/**
	 * @param circleDistance is the distance between the entity and the circle center.
	 * @param circleRadius is the radius of the circle.
	 * @param maxRotation is the maximal rotation of the entity.
	 * @param faceBehaviour is the face behaviour to use to face the target point on the circle.
	 */
	public SteeringEscapeBehaviour() {
		// Do nothing
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public SteeringBehaviourOutput runEscape(Point2d position, Vector2d orientation, double linearSpeed,
			double maxLinearAcc, double angularSpeed, double maxAngularAcc, List<Point2d> obstacle_tab) {
		SteeringBehaviourOutput output = new SteeringBehaviourOutput();
		Vector2d totalRepuls = new Vector2d();
		Vector2d direction = new Vector2d();
		for (Point2d obstacle : obstacle_tab) {
			Vector2d obstacleRepuls = new Vector2d(position.getX() - obstacle.getX(), position.getY() - obstacle.getY());
			double distance = obstacleRepuls.length();
			if (obstacleRepuls.length() < 220) {
				if (obstacleRepuls.length() < 10) {
					obstacleRepuls.normalize();
					obstacleRepuls.scale(orientation.length() / distance);
				} else if (obstacleRepuls.length() < 30)
					obstacleRepuls.scale(Math.exp(1 / distance) + 30);
				else
					obstacleRepuls.scale(Math.exp(1 / distance / 6));
				totalRepuls.setX(totalRepuls.getX() + obstacleRepuls.getX());
				totalRepuls.setY(totalRepuls.getY() + obstacleRepuls.getY());
			}
		}
		for (Point2d obstacle : obstacle_tab) {
			Vector2d obstacleRepuls = new Vector2d(position.getX() - obstacle.getX(), position.getY() - obstacle.getY());
			double distance = obstacleRepuls.length();
			if (obstacleRepuls.length() < 220) {
				obstacleRepuls.scale(Math.exp(8 / distance) + 3);
				totalRepuls.setX(totalRepuls.getX() + obstacleRepuls.getX());
				totalRepuls.setY(totalRepuls.getY() + obstacleRepuls.getY());
			}
		}

		direction.setX(orientation.getX() + totalRepuls.getX());
		direction.setY(orientation.getY() + totalRepuls.getY());

		direction.scale(orientation.length());
		// Angular
		double angular = (new Random().nextDouble() - new Random().nextDouble()) * maxAngularAcc;
		output.setAngular(angular);
		// Linear
		Vector2d linear = new Vector2d(direction);
		linear.normalize();
		output.setLinear(linear);
		return output;
	}

}